package com.nowcoder.community.controller;

import com.nowcoder.community.event.EventProducer;
import com.nowcoder.community.pojo.*;
import com.nowcoder.community.service.CommentService;
import com.nowcoder.community.service.DiscussPostService;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

//Swagger2中要把变量加上
@Api(description = "帖子相关")
@Controller
@RequestMapping("/discusspost")
public class DiscussPostController implements CommunityConstant{

    @Autowired
    @Qualifier("discussPostService")
    private DiscussPostService discussPostService;

    @Autowired
    @Qualifier("userService")
    private UserService userService;

    @Autowired
    @Qualifier("commentService")
    private CommentService commentService;

    @Autowired
    @Qualifier("likeService")
    private LikeService likeService;

    @Autowired
    private EventProducer producer;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation(value = "发布帖子")
    @PostMapping("/add")
    @ResponseBody
    @ApiImplicitParams({
        @ApiImplicitParam(name = "title", value = "帖子标题"),
        @ApiImplicitParam(name = "content", value = "帖子的内容")
    })
    public String addDiscussPost(@RequestParam("title") String title,@RequestParam("content") String content){
        User user = hostHolder.getUser();

        if (user == null){
            return CommunityUtil.getJSONString(403, "请先登录！");
        }

        DiscussPost discussPost = new DiscussPost();
        discussPost.setUserId(user.getId());
        discussPost.setTitle(title);
        discussPost.setContent(content);
        discussPost.setCreateTime(new Date());
        discussPostService.addDiscussPost(discussPost);

        //触发发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(user.getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(discussPost.getId());
        producer.fireEvent(event);

        //计算帖子分数
        String redisKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(redisKey, discussPost.getId());

        return CommunityUtil.getJSONString(0, "发布成功！");
    }

    @ApiOperation(value = "帖子详情")
    @GetMapping("/detail/{id}")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "discusspostId", value = "帖子id"),
        @ApiImplicitParam(name = "page", value = "给帖子分页的实例")
    })
    public String getDiscussPost(@PathVariable("id") int discusspostId, Model model, Page page){
        //帖子
        DiscussPost discussPost = discussPostService.findDiscussPostById(discusspostId);
        System.out.println(discusspostId + "--->" + discussPost);
        model.addAttribute("post", discussPost);
//        System.out.println("---->" + discussPost);

        //作者
        User author = userService.findUserById(discussPost.getUserId());
        model.addAttribute("author", author);

        //当前帖子被点赞的数量
        long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, discusspostId);
        model.addAttribute("likeCount", likeCount);

        //当前帖子被点赞的状态
        int likeStatus = hostHolder.getUser() == null ? 0 :
                likeService.findEntityLikeStatus(hostHolder.getUser().getId(),
                        ENTITY_TYPE_POST, discusspostId);
        model.addAttribute("likeStatus", likeStatus);

        //评论分页信息
        page.setLimit(5);
        page.setPath("/discusspost/detail/" + discusspostId);//
        page.setRows(discussPost.getCommentCount());

        //评论列表
        List<Comment> commentList = commentService.findCommentByEntity(ENTITY_TYPE_POST,
                                                                       discussPost.getId(),
                                                                       page.getOffset(),
                                                                       page.getLimit());

        //评论：给帖子的评论、给评论的评论
        //回复
        //评论VO列表
        List<Map<String, Object>> commentVoList = new ArrayList<>();

        if (commentList != null){
            for (Comment comment : commentList) {
                //容器中存放评论VO信息
                Map<String, Object> commentVo = new HashMap<>();
                //评论
                commentVo.put("comment", comment);

                User commentAuthor = userService.findUserById(comment.getUserId());

                commentAuthor.setHeaderUrl(commentAuthor.getHeaderUrl());

                //此评论发表的作者
                commentVo.put("user", commentAuthor);
//                System.out.println("--->" + commentAuthor);

                //当前评论被点赞的数量
                likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("likeCount", likeCount);

                //当前评论被点赞的状态
                likeStatus = hostHolder.getUser() == null ? 0 :
                        likeService.findEntityLikeStatus(hostHolder.getUser().getId(),
                                ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("likeStatus", likeStatus);

                //每条评论中的回复列表
                List<Comment> replayList = commentService.findCommentByEntity(ENTITY_TYPE_COMMENT,
                        comment.getId(),
                        0, Integer.MAX_VALUE);
//                System.out.println("--->" + replayList);
                //回复VO列表
                List<Map<String, Object>> replayVoList = new ArrayList<>();

                if (replayVoList != null){
                    for (Comment replay : replayList) {

                        //容器中存放回复VO信息
                        Map<String, Object> replayVo = new HashMap<>();

                        //回复信息
                        replayVo.put("replay", replay);

                        //发表回复信息的作者
                        replayVo.put("user", userService.findUserById(replay.getUserId()));

                        //回复的目标用户
                        User targetUser = replay.getTargetId() == 0 ?
                                null : userService.findUserById(replay.getTargetId());//此处是获取目标用户id
                        replayVo.put("target", targetUser);


                        //当前回复被点赞的数量
                        likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, replay.getId());
                        replayVo.put("likeCount", likeCount);

                        //当前回复被点赞的状态
                        likeStatus = hostHolder.getUser() == null ? 0 :
                                likeService.findEntityLikeStatus(hostHolder.getUser().getId(),
                                        ENTITY_TYPE_COMMENT, replay.getId());
                        replayVo.put("likeStatus", likeStatus);

                        replayVoList.add(replayVo);

                    }
                }
                commentVo.put("replays", replayVoList);

                //记录回复数量
                int replayCount = commentService.findCountByEntity(ENTITY_TYPE_COMMENT, comment.getId());
//                System.out.println(comment.getId());
//                System.out.println("--->" + replayCount);
                commentVo.put("replayCount", replayCount);

                commentVoList.add(commentVo);
            }
        }

        model.addAttribute("comments", commentVoList);

        return "site/discuss-detail";
    }

    @ApiOperation(value = "设置帖子置顶")
    @PostMapping("/top")
    @ResponseBody
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "帖子类型id：1为置顶")
    })
    public String setTop(@RequestParam("id") int id){
        //将帖子置顶
        discussPostService.updateType(id, 1);

        //触发发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        producer.fireEvent(event);

        //发帖成功
        return CommunityUtil.getJSONString(0);
    }

    @ApiOperation(value = "给帖子设置为精华")
    @PostMapping("/wonderful")
    @ResponseBody
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "帖子状态id：1为精华")
    })
    public String setWonderful(@RequestParam("id") int id){
        //将帖子设置为精华
        discussPostService.updateStatus(id, 1);

        //触发发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        producer.fireEvent(event);

        //计算帖子分数
        String redisKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(redisKey, id);

        //发帖成功
        return CommunityUtil.getJSONString(0);
    }

    @ApiOperation(value = "删帖")
    @PostMapping("/delete")
    @ResponseBody
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "帖子状态id：2为已拉黑")
    })
    public String setDelete(@RequestParam("id") int id){
        //将帖子设置为精华
        discussPostService.updateStatus(id, 2);

        //触发发帖事件
        Event event = new Event()
                .setTopic(TOPIC_DELETE)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        producer.fireEvent(event);

        //发帖成功
        return CommunityUtil.getJSONString(0);
    }

}
